package cn.itsource.exam.realm;

import cn.itsource.exam.domain.Login;
import cn.itsource.exam.domain.StudentInfo;
import cn.itsource.exam.service.LoginService;
import cn.itsource.exam.service.StudentInfoService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义权限认证授权类
 */
public class StudentOARealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;


    /**
     *授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        String name = principalCollection.getPrimaryPrincipal().toString();
        //根据用户名查询数据库信息
        StudentInfo userInfo  = new StudentInfo();
        userInfo.setName(name);
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
       /* UserInfo stu = userInfoService.selectUserInfoByName(userInfo);
        //添加角色和权限

        for (Role role:userInfo.getRoles()){
            //添加角色
            simpleAuthorizationInfo.addRole(role.getName());
            //添加权限
            for(Permission permission:role.getPermissions()){
                simpleAuthorizationInfo.addStringPermission(permission.getName());
            }
        }*/
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        Object principal = authenticationToken.getPrincipal();
        if(principal==null){
            return null;
        }
        //获取用户信息
        String name = principal.toString();
        Map<String,Object> map = new HashMap<>();
        map.put("name",name);
        Login user = loginService.selectUserInfoByName(map);
        if(user== null){
            return null;
        }else{
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(name, user.getPassword(), user.getName());
            return authenticationInfo;
        }
    }
}
